package com.tin.controller;

import com.mysql.cj.x.protobuf.MysqlxDatatypes;
import com.tin.bean.Msg;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.HashMap;
import java.util.Map;

/**
 * @author liming_oicq@163.com
 * @date 2018-10-13 00:37
 * springboot默认全局异常处理器，将错误重定向至/error；通过自定义controller映射到/error，实现对错误请求的处理
 */
@Controller
public class MyErrorController implements ErrorController {

    private final String ERROR_PATH = "/error";

    @RequestMapping(value = ERROR_PATH)
    @ResponseBody
    public Msg error(HttpServletRequest request) {
        Integer  statusCode = (Integer)request.getAttribute("javax.servlet.error.status_code");

        if (statusCode == HttpStatus.NOT_FOUND.value())  //404
            return new Msg(String.valueOf(statusCode), HttpStatus.NOT_FOUND.getReasonPhrase());
        else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value())  //500
            return new Msg(String.valueOf(statusCode), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
        else
            return new Msg("999", "系统错误，请联系管理员");

    }

    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }
}
